#include "GameServer.h"
#include "JME_JsonFile.h"
#include "JME_Core.h"
#include "DispatchHandler.h"
#include "JME_RpcHandler.h"
#include "GameRPCHandler.h"

GameServer::GameServer()
{
}

GameServer::~GameServer()
{

}


GameServer::GateServerPtr GameServer::getInstance()
{
	static GateServerPtr _pInstance = GateServerPtr(new GameServer);
	return _pInstance;
}

void GameServer::init()
{
	auto& dbConf = _config["mongo"];
	_mongoDBPool = MongoDBPool::create(4, boost::bind(connectMongoDB, _1, dbConf["addr"].asString(), dbConf["dbname"].asString(), dbConf["username"].asString(), dbConf["passwd"].asString()));

	DispatchHandler::init();

	JME_RpcHandler::bindHandler<GameRpcHandler>();
}

MongoDBPool* GameServer::getMongoDBPool()
{
	return _mongoDBPool.get();
}


bool connectMongoDB(JME_MongoConnection* conn, const string& ip_str, const string& db_name, const string& name, const string& pwd)
{
	std::string errorStr;
	if(!conn->connect(ip_str, &errorStr))
	{
		std::cout << errorStr << std::endl;
		throw std::runtime_error(errorStr);
	}
	if ( !conn->auth(db_name, name , pwd, &errorStr) )
	{
		std::cout << errorStr << std::endl;
		throw std::runtime_error(errorStr);
	}
	return true;
}

